﻿
class CsvHandler
  def initialize(fileName)
    @file = fileName
  end
  
  def getWines()
    result = Array.new(0)
    CSV.foreach(@file, :headers => true, :col_sep => ";", :encoding => "UTF-8") do |csv_wine|
      result << csvToWine(csv_wine)
    end
    (result)
  end
  
  def saveWines(wines)
	line=0
	CSV.open(@file, "wb", :col_sep => ";", :force_quotes=>true, :encoding => "UTF-8") do |csv|
		csv << self.getCsvHeader
		
		wines.each do |w|
			
			line += 1
			csv << self.wineToCsv(w)
		end  
	end 
	$log.debug "Wrote #{line} lines into #{@file}"
  end
  
	def  getCsvHeader
		result = Array.[]("Name","Eingelagert","Jahrgang","Land","Produzent","Region","Kategorie",
		"Größe (in l)","Rebsorte","Lagerort","Initialer Bestand","Aktueller Bestand","Preis","Alkoholgehalt","Bewertung","Notiz","Lagerdauer",
		"EAN-Code","EAN-Code Format","Favorit","Währung","UUID","Version","Kellername","Keller-UUID","Kontakt","Typ","Longitude","Latitude",)
		(result)
	end
  
	def wineToCsv(wine)
		result = Array.[](
			wine.name,
			nil,
			wine.year,
			wine.country,
			wine.producer,
			wine.region,
			wine.category,
			nil,
			wine.type,
			nil,
			1,
			0,
			nil,
			wine.alcohol,
			nil,
			"Source: "+wine.source,
			nil,
			wine.ean,
			"EAN_13",
			nil,
			"EUR",
			nil,
			nil,
			nil,
			nil,
			nil,
			nil,
			nil,
			nil
		)
		
		(result)
	end
  
  def  csvToWine(rowAsHash)
    result = Wine.new
    result.name = rowAsHash["Name"]
    
    result.year = rowAsHash["Jahrgang"]
    result.country = rowAsHash["Land"]
    result.producer = rowAsHash["Produzent"]
    result.region = rowAsHash["Region"]
    result.category = rowAsHash["Kategorie"]
    result.type = rowAsHash["Rebsorte"]
    result.ean = rowAsHash["EAN-Code"]
    
    (result)
  end
end